//公共js，主要做表单验证，以及基本方法封装
const utils = {
  enum: function(type, code) {
    let list = require('../config/enum');
    return list[type][code] || '';
  },
  isNullOrEmpty: function(value) {
    //是否为空
    return (value === null || value === '' || value === undefined) ? true : false;
  },
  trim: function(value) {
    //去空格
    return value.replace(/(^\s*)|(\s*$)/g, "");
  },
  isMobile: function(value) {
    //是否为手机号
    return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
  },
  isFloat: function(value) {
    //金额，只允许保留两位小数
    return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
  },
  isNum: function(value) {
    //是否全为数字
    return /^[0-9]+$/.test(value);
  },
  formatNum: function(num) {
    //格式化手机号码
    if (utils.isMobile(num)) {
      num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
    }
    return num;
  },
  formatAmount: function (amount, decimal = 2) {
    return Number(amount).toFixed(decimal).split('.');
  },
  interfaceUrl: function(apiRoute) {
    let config = require('../config/base');
    let api = '', apiPath = '', apiMethod = '';
    if (apiRoute) {
      //获取API地址
      let [fileName, apiName, second] = apiRoute.split('.');
      let apis = require(`../apis/${fileName}`);
      api = second ? apis[apiName][second] : apis[apiName];
      apiPath = api['path'] || api;
      apiMethod = api['method'] || 'GET';
      if (!apiPath) console.log(`路由错误：${apiRoute}`);
      //apiPath += `?merchant_id=${config.merchantId}&access-token=${wx.getStorageSync('rf_token')}`;
      apiPath += `?access-token=${wx.getStorageSync('rf_token')}`;
    }
    //接口地址
    return {url: config.baseUrl + (config.apiVer || '') + apiPath, method: apiMethod};
  },
  toast: function(text, duration, success) {
    wx.showToast({
      title: text,
      icon: success ? 'success' : 'none',
      duration: duration || 2000
    });
  },
  preventMultiple: function(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
      gapTime = 200;
    }
    let lastTime = null;
    return function() {
      let now = +new Date();
      if (!lastTime || now - lastTime > gapTime) {
        fn.apply(this, arguments);
        lastTime = now;
      }
    }
  },
  request: function(apiRoute, data, type, hideLoading) {
    //接口请求
    if (!hideLoading) {
      wx.showLoading({
        title: '请稍候...',
        mask: true
      });
    }
    if (typeof apiRoute == 'object' || apiRoute.indexOf('pages') > -1 || !apiRoute) {
      // 页面路径为api路由
      let pages = getCurrentPages();
      let curPage = apiRoute.route || apiRoute || pages[pages.length - 1].route;
      apiRoute = curPage.slice(curPage.indexOf('/') + 1).replace(/\//g, '.');
    }
    /*let urlQuery = data && data.get ? data.get : '';
    let postData = data && data.post ? data.post : '';*/
    if (data) {
      var {query, body} = data;
    }
    let {url, method} = this.interfaceUrl(apiRoute);
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${url}&${query}`,
        data: body,
        header: {
          'content-type': type ? 'application/x-www-form-urlencoded' : 'application/json'
        },
        method: method, // 'GET', 'POST', 'PUT', 'DELETE'
        dataType: 'json',
        success: response => {
          !hideLoading && wx.hideLoading();
          let result = response.data;
          let statusCode = require('../config/statusCode').request;
          let errMsg = statusCode[result.code];
          if (result.code == 200) {
            resolve(result.data);
          } else if (errMsg) {
            console.log(`${apiRoute}: (${result.code})${result.message}`);
            this.toast(result.code == 422 ? result.message : errMsg);
          } else {
            reject(new Error(result.message));
          }
        },
        fail: error => {
          !hideLoading && this.toast("网络不给力，请稍后再试~");
          reject(error);
        }
      })
    });
  },
  uploadFile: function(apiRoute, imgPath) {
    wx.showLoading({
      title: '请稍候...',
      mask: true
    });
    return new Promise((resolve, reject) => {
      const uploadTask = wx.uploadFile({
        url: this.interfaceUrl(apiRoute),
        filePath: imgPath,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        formData: {},
        success: response => {
          wx.hideLoading();
          let d = JSON.parse(error.data);
          if (d.code === 1) {
            let fileObj = JSON.parse(d.data)[0];
            //文件上传成功后把图片路径数据提交到服务器，数据提交成功后，再进行下张图片的上传
            resolve(fileObj);
          } else {
            this.toast(error.message);
          }
        },
        fail: error => {
          reject(error);
          wx.hideLoading();
          this.toast(error.message);
        }
      })
    })
  }
}

module.exports = {
  enum: utils.enum ,
  isNullOrEmpty: utils.isNullOrEmpty,
  trim: utils.trim,
  isMobile: utils.isMobile,
  isFloat: utils.isFloat,
  isNum: utils.isNum,
  interfaceUrl: utils.interfaceUrl,
  toast: utils.toast,
  request: utils.request,
  uploadFile: utils.uploadFile,
  formatNum: utils.formatNum,
  formatAmount: utils.formatAmount
}